package com.learn.kafka.partition;

import com.learn.kafka.config.ProducerProperties;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.common.PartitionInfo;

import java.util.List;

/**
 * 获取Kafka主题的分区信息（继承通用生产者配置）
 * @author: learn.kafka
 */
public class PartitionInformation extends ProducerProperties {
    public static void main(String[] args) {
        new PartitionInformation().getPartitionDetails();
    }
    // 构造方法：可根据需要覆盖父类配置
    public PartitionInformation() {
        super(); // 调用父类构造方法，加载通用配置
        // 如需修改配置，可在此处覆盖
        // 例如：setConfig("bootstrap.servers", "192.168.44.160:9092");
    }

    // 获取并打印主题的分区信息
    private void getPartitionDetails() {
        // 从父类获取生产者实例
        Producer<Integer, String> producer = createProducer();

        try {
            // 获取指定主题的分区信息
            List<PartitionInfo> partitions = producer.partitionsFor("mytopic");

            // 遍历打印分区详情
            for (PartitionInfo partition : partitions) {
                System.out.println("分区ID: " + partition.partition());
                System.out.println("分区leader节点: " + partition.leader());
                System.out.println("副本节点: " + partition.replicas());
                System.out.println("同步副本节点: " + partition.inSyncReplicas());
                System.out.println("------------------------");
            }
        } finally {
            // 关闭生产者
            producer.close();
        }
    }
}
